import SwiftUI

struct NodeView: View {
    @State private var vpnConfigs: [VpnConfig] = []
    @State private var selectedHotId: Int? = nil // 初始化为 nil，等到加载完成再设置

    @Environment(\.presentationMode) var presentationMode

    @State private var errorMessage: String?

    var body: some View {
        ZStack {
            VStack {
                Back(title: "Choice", onBackTap: {
                    self.presentationMode.wrappedValue.dismiss()
                    if let selectedHotId = selectedHotId {
                        UserDefaultsManager.shared.setInt(selectedHotId, forKey: "vpnList")
                    }
                })

                if let errorMessage = errorMessage {
                    Text("Error: \(errorMessage)")
                        .foregroundColor(.red)
                        .padding()
                } else {
                    List($vpnConfigs, id: \.converterPdfId) { $config in
                        VStack {
                            HStack {
                                Text(config.converterPdfName)
                                    .foregroundColor(Color.black)
                                Spacer()
                                RadioButton(isSelected: selectedHotId == config.converterPdfId) { // 传递 config ID
                                    selectedHotId = config.converterPdfId // 更新 selectedHotId
                                }
                            }
                            .background(Color.white)
                            .padding(.vertical, 8)
                        }
                        .listRowBackground(Color.white)
                    }
                    .background(Color.white)
                    .listStyle(PlainListStyle())
                }

                Spacer()
            }
            .onAppear {
                NetworkManager().fetchVpnConfig { configs in
                    vpnConfigs = configs
                    if selectedHotId == nil, let firstConfig = configs.first {
                        selectedHotId = firstConfig.converterPdfId
                    }
                } failure: { error in
                    errorMessage = error.localizedDescription
                }
            }
        }
        .navigationBarHidden(true)
        .navigationBarBackButtonHidden(true)
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct RadioButton: View {
    var isSelected: Bool
    var action: () -> Void

    var body: some View {
        Button(action: {
            action()
        }) {
            Image(systemName: isSelected ? "largecircle.fill.circle" : "circle")
                .foregroundColor(isSelected ? .blue : .black)
                .font(.system(size: 24))
        }
        .buttonStyle(PlainButtonStyle())
    }
}

struct LNodeView_Previews: PreviewProvider {
    static var previews: some View {
        NodeView()
    }
}
